'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 副本
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var moment = require('moment');
var _ = require('lodash');
var copyItemSchema = require('./copy/copyItemSchema');
var starItemSchema = require('./copy/starItemSchema');
var copyMgr = require('../mgr/copyMgr');
var blackMarketConf = require('../config/blackMarketConf.js');
var constantUtil = require('../util/constantUtil.js');

/**
 * 初始化扫荡次数
 * @return {[type]} [description]
 */
var _initTotalSweepNum = function () {
    return 10;
};

/**
 * 黑市商品id
 * @return {[type]} [description]
 */
var _blackMarketList = function () {
    var shop_list = [];
    var list = blackMarketConf.getBlackMarketReward();
    _.each(list, function (item) {
        shop_list.push(item.id);
    });
    return shop_list;
};

/**
 * 初始化黑市每日触发次数
 * @return {[type]} [description]
 */
var _blackMarketNum = function () {
    return constantUtil.value('black_market_appear_time');
};

/**
 * 初始化精英副本最大可攻打次数
 * @return {[type]} [description]
 */
var _initHardCarbonTimes = function () {
    return constantUtil.value('hard_carbon_times');
};

/**
 * 精英副本攻打次数信息
 */
var fightTimesItem = new mongoose.Schema({
    // 副本ID
    copy_id: Number,
    // 当天攻打次数
    fight_times: Number,
});

/**
 * 副本
 */
var copySchema = new mongoose.Schema({
    // 玩家id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 已经扫荡的次数
    sweep_num: {
        type: Number,
        default: 0
    },

    // 总的可以扫荡次数
    total_sweep_num: {
        type: Number,
        default: _initTotalSweepNum
    },

    // 总的可以扫荡次数
    buy_sweep_num: {
        type: Number,
        default: 0
    },

    // 每日副本体力消耗统计
    copy_total_energy: {
        type: Number,
        default: 0
    },

    // 黑市体力消耗累计
    total_energy: {
        type: Number,
        default: 0
    },

    // 黑市次数
    black_market_num: {
        type: Number,
        default: _blackMarketNum
    },

    // 黑市结束时间
    is_end_time: {
        type: Number,
        default: 0
    },

    // 黑市列表
    black_market_list: {
        type: [Number],
        default: _blackMarketList
    },

    // 黑市已购买列表
    buy_list: [Number],

    // 副本列表
    copy_list: [copyItemSchema],

    // 副本星级奖励
    star_reward_list: [starItemSchema],

    // 上次刷新时间
    last_refresh_time: {
        type: Date,
        default: 0
    },

    // 副本双倍经验卡使用次数
    copy_double_exp_num: {
        type: Number,
        default: 0
    },

    // 精英副本当天攻打次数
    fight_times_list: {
        type: [fightTimesItem],
        default: []
    },

    // 精英副本最大次数
    max_hard_carbon_times: {
        type: Number,
        default: _initHardCarbonTimes
    },
});

copySchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 黑市体力统计
 * @param  {[type]} copy_id [description]
 * @return {[type]}         [description]
 */
copySchema.methods.addTotalEnergy = function (add_energy) {
    this.total_energy += add_energy;
};

/**
 * 查询精英副本攻打次数
 */
copySchema.methods.getHardCarbonTimes = function (copy_id) {
    var copy_item = _.find(this.fight_times_list, {
        copy_id: copy_id
    });
    if (!!copy_item) {
        return copy_item.fight_times;
    }
    return 0;
};

/**
 * 设置VIP增加精英副本攻打次数
 */
copySchema.methods.addVipAddHardCarbonTimes = function (vip_add_times) {
    var hard_carbon_times = constantUtil.value('hard_carbon_times');
    this.max_hard_carbon_times = vip_add_times + hard_carbon_times;
};

/**
 * 查询精英副本最大攻打次数
 */
copySchema.methods.getMaxHardCarbonTimes = function () {
    return this.max_hard_carbon_times;
};

/**
 * 累加精英副本当天攻打次数
 */
copySchema.methods.addHardCarbonTimes = function (copy_id) {
    var copy_item = _.find(this.fight_times_list, {
        copy_id: copy_id
    });
    if (!!copy_item) {
        if (copy_item.fight_times >= this.getMaxHardCarbonTimes()) {
            return false;
        }
        copy_item.fight_times++;
    } else {
        this.fight_times_list.push({
            copy_id: copy_id,
            fight_times: 1
        });
    }
    return true;
};

/**
 * 黑市结束时间
 * @param  {[type]} copy_id [description]
 * @return {[type]}         [description]
 */
copySchema.methods.setBlackMarketEndTime = function () {
    this.is_end_time = moment().unix() + constantUtil.value('black_market_keep_time');
};

/**
 * 扣除黑市次数
 * @param  {[type]} copy_id [description]
 * @return {[type]}         [description]
 */
copySchema.methods.subBlackMarketNum = function () {
    if (this.black_market_num >= 1) {
        this.black_market_num--;
        return true;
    } else {
        return false;
    }
};

/**
 * 重置黑市列表
 * @param  {[type]} copy_id [description]
 * @return {[type]}         [description]
 */
copySchema.methods.resBlackmarketList = function () {
    var self = this;
    self.black_market_list = _blackMarketList();
    this.buy_list = [];
};

/**
 * 增加购买记录
 * @param  {[type]} copy_id [description]
 * @return {[type]}         [description]
 */
copySchema.methods.addBuyId = function (shop_id) {
    if (_.indexOf(this.buy_list, shop_id) == -1) {
        this.buy_list.push(shop_id);
        return true;
    } else {
        return false;
    }
};

/**
 * 获取双倍副本经验道具卡使用次数
 * @param  {[type]} copy_id [description]
 * @return {[type]}         [description]
 */
copySchema.methods.getDoubleCopyExpNum = function (copy_double_exp_num) {
    return this.copy_double_exp_num;
};

/**
 * 增加双倍副本经验道具卡使用次数
 * @param  {[type]} copy_id [description]
 * @return {[type]}         [description]
 */
copySchema.methods.addDoubleCopyExpNum = function (add_copy_double_exp_num) {
    this.copy_double_exp_num += +add_copy_double_exp_num;
};

/**
 * 扣除双倍副本经验道具卡使用次数
 * @param  {[type]} copy_id [description]
 * @return {[type]}         [description]
 */
copySchema.methods.subDoubleCopyExpNum = function () {
    this.copy_double_exp_num--;
};

/**
 * 添加奖励
 * @param  {[type]} copy_id [description]
 * @return {[type]}         [description]
 */
copySchema.methods.addStarReward = function (main_coyp_id, position) {
    var chapter_list = [];
    var reward_list = [];
    var star_reward_list = this.star_reward_list;
    _.each(star_reward_list, function (star_reward_item) {
        chapter_list.push(star_reward_item.getCopyChapter());
    });

    if (_.indexOf(chapter_list, main_coyp_id) == -1) {
        reward_list.push(position);
        this.star_reward_list.push({
            copy_chapter: main_coyp_id,
            reward_list: reward_list
        });
        return true;
    }

    for (var i = this.star_reward_list.length - 1; i >= 0; i--) {
        var star_reward_item = this.star_reward_list[i];
        if (star_reward_item.getCopyChapter() == main_coyp_id) {
            if (!star_reward_item.addRewardList(position)) {
                return false;
            }
            return true;
        }
    }
};

/**
 * 统计每个副本章节的总星星数
 * @param  {[type]} copy_id [description]
 * @return {[type]}         [description]
 */
copySchema.methods.getTotalStarNum = function (main_copy_id) {
    var copy_list = this.copy_list;
    var total_star_num = 0;
    _.each(copy_list, function (copy_item) {
        var copy_chapter = parseInt(copy_item.copy_id / 100);
        if (copy_chapter == main_copy_id) {
            total_star_num += copy_item.star;
        }
    });
    return total_star_num;
};

/**
 * 获取副本数据
 * @param  {[type]} copy_id [description]
 * @return {[type]}         [description]
 */
copySchema.methods.getCopy = function (copy_id) {
    for (var i = 0; i < this.copy_list.length; i++) {
        var copy = this.copy_list[i];
        if (copy.copy_id == copy_id) {
            return copy;
        }
    }
    return null;
};

/**
 * 通关副本
 * @param  {[type]} copy_id [description]
 * @param  {[type]} star    [description]
 * @return {[type]}         [description]
 */
copySchema.methods.passCopy = function (copy_id, star) {
    var copy = this.getCopy(copy_id);
    if (!copy) {
        this.copy_list.push({
            copy_id: copy_id,
            star: star
        });
    } else {
        if (copy.star < star) {
            copy.star = star;
        }
    }
};

/**
 * 刷新
 * @return {[type]} [description]
 */
copySchema.methods.refresh = function () {
    this.last_refresh_time = Date.now();
    this.sweep_num = 0;
    this.total_sweep_num = _initTotalSweepNum();
    this.buy_sweep_num = 0;
    this.black_market_num = _blackMarketNum();
    this.total_energy = 0;
    // this.remove_fight_times_list = [];
    // _.forEach(this.fight_times_list, function (item) {
    //     this.remove_fight_times_list.push(item);
    // });
    this.fight_times_list = [];
};

/**
 * 获取上次刷新的时间
 * @return {[type]} [description]
 */
copySchema.methods.getLastRefreshTime = function () {
    return this.last_refresh_time;
};

/**
 * 获取修改
 * @return {[type]} [description]
 */
copySchema.methods.getLastChange = function () {
    var json_data = this.toJSON();
    var copy_list = [];
    _.each(this.copy_list, function (copy_item) {
        if (!!copy_item.isModified()) {
            copy_list.push(copy_item);
        }
    });
    json_data.copy_list = copy_list;

    // 精英副本战斗次数
    var fight_times_list = [];
    _.each(this.fight_times_list, function (fight_times_item) {
        if (!!fight_times_item.isModified()) {
            fight_times_list.push(fight_times_item);
        }
    });
    json_data.fight_times_list = fight_times_list;

    // var remove_fight_times_list = [];
    // _.each(this.remove_fight_times_list, function (remove_fight_times_item) {
    //     remove_fight_times_list.push(remove_fight_times_item);
    // });
    // this.remove_fight_times_list = [];
    // json_data.remove_fight_times_list = remove_fight_times_list;

    return json_data;
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
copySchema.methods.push = function () {
    copyMgr.sendCopyChanged(
        this.role_id,
        this.toJSON(),
        function (err, fails) {
            if (err) {
                console.error('send copy message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

copySchema.methods.pushModify = function () {
    copyMgr.sendCopyChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send copy message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!copySchema.options.toJSON) {
    copySchema.options.toJSON = {};
}
/* jshint unused:false */
copySchema.options.toJSON.transform = function (doc, ret) {
    delete ret.role_id;
    delete ret.last_refresh_time;
    delete ret._id;
    delete ret.__v;
};

mongoose.model('Copy', copySchema);
